package com.demo.netty.handlesort;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

public class ClientInboundHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf byteBuf = ctx.alloc().buffer(12);
        byteBuf.writeBytes("i am client 1".getBytes() );
        ctx.channel().writeAndFlush(byteBuf);
        new ThreadRobot(ctx).start();
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        byteBuf.markReaderIndex();
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        System.out.print("receive message from server:");
        System.out.println(new String(bytes));
//        System.out.println(ctx);
        byteBuf.release();
//        byteBuf.resetReaderIndex();
//        ctx.channel().writeAndFlush(byteBuf);
    }

    class ThreadRobot extends Thread{
        ChannelHandlerContext ctx;
        public ThreadRobot(ChannelHandlerContext ctx){
            this.ctx = ctx;
        }

        @Override
        public void run(){
            int i=0;
            for(;;){
                ByteBuf byteBuf = this.ctx.alloc().buffer(10);
                byteBuf.writeBytes("iam robot".getBytes());
                ChannelFuture future = this.ctx.writeAndFlush(byteBuf);
                future.addListeners(new GenericFutureListener<Future<? super Void>>() {
                    @Override
                    public void operationComplete(Future<? super Void> future) throws Exception {
                        System.out.println(future.get());
                    }
                });
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                if(i++==3){
//                    this.ctx.channel().close();
//                }
            }
        }

    }
}
